import { Screen, UITransform, v2, v3, Vec2 } from "cc";
import { BattleObj } from "../BattleObj";
import { BehaviorScript } from "../BehaviorScript";
import { GameCtx } from "../../GameCtx";
import { Enum_PropType } from "../Enum_PropType";

export class CommonMonsterBehaviorScript implements BehaviorScript{
    id: number = 1;
    cfgId: number = 1;
    target:BattleObj 
    targetPos:Vec2;
    sleep:boolean = false; //是否睡眠状态，睡眠状态下不执行行为脚本
    constructor(target:BattleObj ) {
        this.target = target;
    }
    update(dt: number): void {
        //TODO 检测状态是否能移动

        let nowPos = this.target.node.position
        if(!this.targetPos){
            let size = GameCtx.ins.screenSize
            let randomX = -size.width/2 + Math.random() * size.width
            let randomY = -size.height/2 + Math.random() * size.height
            this.targetPos = new Vec2(randomX, randomY)
        }
        let dir = Vec2.distance(v2(nowPos.x,nowPos.y),this.targetPos)
        if(dir<5 && !this.sleep){//到达目的地后停顿以下
            this.sleep = true
            this.target.scheduleOnce(()=>{
                this.sleep = false;
                this.targetPos = null; //清除目标位置，重新生成
            },1)
            return
        }
        //移动到目标位置
        let speed = this.target.propSet.get(Enum_PropType.Speed)
        if(!speed || speed<=0){
            return; //速度为0时不移动
        }
        let moveDir = v3(this.targetPos.x - nowPos.x, this.targetPos.y - nowPos.y,0);
        moveDir = moveDir.normalize();
        let moveStep = moveDir.multiplyScalar(speed * dt);

        let newPos = this.target.node.position.add(moveStep) 
        this.target.node.setPosition(newPos)
    }

    stop(): void {

    }

}